# coding:utf-8
# author: Livingbody
# date: 2020.05.06

from flask import Flask, render_template, request, jsonify,Blueprint
from werkzeug.utils import secure_filename
import os
import requests
import base64
import json
import time
import cv2
import numpy as np 
index_koutu = Blueprint("koutu", __name__)
# 设置允许的文件格式
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'bmp', 'jpeg'])
# 当前文件所在路径
basepath = os.path.dirname(__file__)


def allowed_file(filename):
    filename = filename.lower()
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


# 上传并抠图
@index_koutu.route('/koutu', methods=['POST', 'GET'])  # 添加路由
def upload():
    if request.method == 'POST':
        try:
            f = request.files['file']
            if not (f and allowed_file(f.filename)):
                return jsonify({"error": 1001, "msg": "请检查上传的图片类型，仅限于png、PNG、jpg、JPG、bmp"})
                # return render_template('404.html')
            # sourcefile = os.path.join('static/images/source', secure_filename(f.filename))
            sourcefile = 'static/images/source/'+secure_filename(f.filename)
            # sourcefile = 'static/images/source/'+f.filename
            print('上传路径',sourcefile)

            # upload_path = os.path.join(basepath, sourcefile)  # 注意：没有的文件夹一定要先创建，不然会提示没有该路径
            upload_path = sourcefile

            f.save(upload_path)

            filename = convert(upload_path)

            # filename = os.path.join('static/images/target', filename)
            filename = 'static/images/target/'+ filename

            print('识别结果路径',filename)

            return render_template('koutu_ok.html', val1=time.time(), sourcefile=sourcefile, filename=filename)
            # return render_template('zhengjianzhao_ok.html', val1=time.time(), sourcefile=sourcefile, filename=filename)
        except Exception:
            return render_template('404.html')
    return render_template('koutu.html')


def cv2_to_base64(image):
    data = cv2.imencode('.jpg', image)[1]
    return base64.b64encode(data.tostring()).decode('utf8')


# 去除背景色
# 最新方法
# https://github.com/PaddlePaddle/PaddleHub/blob/release/v1.6/docs/tutorial/serving.md
def convert(upload_path):
    file_list = [upload_path]

    print('文件列表',file_list)
    imgOrigin = cv2.imread(file_list[0])
    # files = [("image", (open(item, "rb"))) for item in file_list]
    files = {'images':[cv2_to_base64(cv2.imread(file_list[0]))]}

    # 指定图片分割方法为deeplabv3p_xception65_humanseg并发送post请求
    # url = "http://127.0.0.1:8866/predict/image/deeplabv3p_xception65_humanseg"
    url = "http://127.0.0.1:8866/predict/deeplabv3p_xception65_humanseg"
    headers = {"Content-Type": "application/json"}
    print('header',headers)
    # r = requests.post(url=url,  headers=headers, files=files)
    r = requests.post(url=url,  headers=headers, data=json.dumps(files))
    
    print('返回状态',r.status_code)

    t = int(time.time())
    filename = str(t) + '.png'
    
    
    if (r.status_code != 200):
        return '404'

    results = r.json()["results"]
    for item in results:
        # {'msg': '', 'results': [{'data': '/9jdsdsdx
        # mypath = os.path.join(basepath, 'static/images/target', filename)
        mypath = 'static/images/target/'+filename

        imageOri = imgOrigin.copy()
        print('imageOri 读取后')
        # cv2.imshow('原图',imageOri)

        imageMask = base64.b64decode(item["data"].split(',')[-1]);
        
        nparr=np.fromstring(imageMask,np.uint8) 
        img_decode=cv2.imdecode(nparr,1)
        # png 转到灰度
        img_decode = cv2.cvtColor(img_decode,cv2.COLOR_BGR2GRAY)
        print('imageMask 解码后')
        # 分离出3个颜色通道
        b_channel, g_channel, r_channel = cv2.split(imageOri)
        # 将alpha通道合并到原来的图片上
        img_BGRA = cv2.merge((b_channel, g_channel, r_channel, img_decode)) # 
        cv2.imwrite(mypath,img_BGRA) # 可以正常保存
    return filename
